package com.sakura.system.controller.upload.voide;



import com.sakura.system.entity.upload.SrWebFilevideo;
import com.sakura.system.service.impl.uploadimpl.SrWebFilevideoServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/upload/file/video")
public class FileVideoController {
//    读取配置文件
    @Value("${file.upload-video}")
    private String uploadDir;

    @Autowired
    private HttpServletRequest request;

    @Autowired
//    private SrWebFilevideoServiceImpl service;
    private SrWebFilevideoServiceImpl service;

    /**
     * 获取文件扩展名
     *
     * @param filename 文件名
     * @return 扩展名
     */
    private String getFileExtension(String filename) {
        int dotIndex = filename.lastIndexOf(".");
        if (dotIndex > 0 && dotIndex < filename.length() - 1) {
            return filename.substring(dotIndex + 1).toLowerCase();
        }
        return "";
    }

    /**
     * 检查文件类型是否允许上传
     *
     * @param extension         文件扩展名
     * @param allowedFileTypes  允许上传的文件类型数组
     * @return 是否允许上传
     */
    private boolean isFileTypeAllowed(String extension, String[] allowedFileTypes) {
        for (String allowedType : allowedFileTypes) {
            if (allowedType.equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }


    // 上传视频
    @PostMapping("/uploadVideo")
    /**
     * 上传视频文件处理方法
     *
     * @param video 要上传的视频文件
     * @return 上传成功的消息
     * @throws IOException 如果发生I/O错误
     */
    public String uploadVideo(@RequestParam("video") MultipartFile video) throws IOException {
        // 检查文件类型
        String[] allowedFileTypes = {"mp4", "avi", "mov","ts","rm"};
        // 获取文件扩展名
        String extension = getFileExtension(video.getOriginalFilename());
        // 检查文件名称是否合格
        if (!isFileTypeAllowed(extension, allowedFileTypes)) {
            return "Invalid file type. Only MP4, AVI, and MOV files are allowed.";
        }

        // 生成当前日期作为文件夹名
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String folderName = dateFormat.format(new Date());

        // 创建日期文件夹
        File folder = new File(uploadDir, folderName);
//        log.info("文件夹创建：");
        log.info(String.valueOf(folder.exists()));
        if (!folder.exists()) {
            folder.mkdirs();
//            log.info(folder.toString());
//            log.info("创建文件成功");
        } else {
//            log.info("文件夹已存在");
        }

        // 获取域名或IP和端口号
        String domain;
        if (request.getServerName().equals("localhost") || request.getServerName().equals("127.0.0.1")) {
            // 使用IP访问时，获取IP和端口号
            domain = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
        } else {
            // 使用域名访问时，只获取域名
            domain = request.getScheme() + "://" + request.getServerName();
        }

        // 生成唯一的文件名
//        String filename = UUID.randomUUID().toString() + video.getOriginalFilename();
        String filename = UUID.randomUUID().toString() +'.'+ extension;

        // 创建目标文件对象
        File destFile = new File(folder, filename);
        log.info(destFile.toString());

        // 将文件字节数组写入目标文件
        try {
            FileUtils.writeByteArrayToFile(destFile, video.getBytes());
        } catch (Exception e) {
            return "保存失败!请重试!";
        }

        // 拼接文件访问地址，去掉前缀部分
        // 获取下标
        int index = destFile.toString().indexOf("upload");
        String result = destFile.toString().substring(index);
        String fileUrl = domain + "/" + result;
        log.info(fileUrl);

        SrWebFilevideo srWebFilevideo = new SrWebFilevideo();
        srWebFilevideo.setName(filename);
        srWebFilevideo.setUrl(fileUrl);

        if (service.save(null,srWebFilevideo).equals(false)){
            return null;
        }

        // 返回数据
        return "{\"status\": \"success\", \"filename\": \"" + filename + "\", \"fileUrl\": \"" + fileUrl + "\"}";

    }





}
